package cn.summit;

import cn.summit.realm.Md5RealM;
import cn.summit.realm.MyRealm;
import com.sun.media.sound.SoftTuning;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

/**
 * @author summit
 * @since 2020/12/18 23:14
 */
public class Md5RealmMainTest {

    public static void main(String[] args) {
        // 1.安全管理对象
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        //2.realm
        Md5RealM md5Realm = new Md5RealM();
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(1024);
        md5Realm.setCredentialsMatcher(matcher);

        securityManager.setRealm(md5Realm);

        //3.给安全工具设置 安全管理器
        SecurityUtils.setSecurityManager(securityManager);

        //4.获取主体对象
        Subject subject = SecurityUtils.getSubject();

        // 身份凭证
        UsernamePasswordToken token = new UsernamePasswordToken("summit", "123456");
        System.out.println(subject.isAuthenticated());
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            System.out.println("账号不存在");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
        }
        System.out.println(subject.isAuthenticated());
        if (subject.isAuthenticated()) {
            subject.hasRole("admin");
            System.out.println("当前角色权限"+subject.hasRole("admin"));
            System.out.println("当前所有角色权限"+subject.hasAllRoles(Arrays.asList("admin","user")));
            boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "user","stu"));
            System.out.println("=============");
            for (boolean aBoolean : booleans) {
                System.out.println(aBoolean);
            }

            System.out.println("资源权限认证=========");
            System.out.println(subject.isPermitted("admin:test:01"));

        }

    }
}
